package com.wheatek.wtklib.widget;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;

/**
 * 自定义加载进度对话框
 * Created by Administrator on 2016-10-28.
 */

public class LoadingDialog {
    private ProgressDialog mDialog;

    private Context mContext;

    public LoadingDialog(Context context) {
        mContext = context;
        if (mDialog == null) {
            mDialog = new ProgressDialog(context, ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        }
    }

    private DialogInterface.OnKeyListener keylistener = (dialog, keyCode, event) -> {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            return true;
        } else {
            return false;
        }
    };

    public void setMessage(String message) {
        mDialog.setMessage(message);

    }

    public void show() {
        if (!((Activity) mContext).isFinishing() && !mDialog.isShowing()) {
            mDialog.show();
        }
    }

    public void dismiss() {
        if (mDialog != null && !((Activity) mContext).isFinishing() && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    /**
     * 设置点击dialog以外的地方是否dismiss掉
     *
     * @param flag
     */
    public void setCanceledOnTouchOutside(boolean flag) {
        mDialog.setCanceledOnTouchOutside(flag);
        if (!flag) {
            mDialog.setCancelable(false);
            mDialog.setOnKeyListener(keylistener);
        }
    }
}
